package cn.kgm.generator.utils;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgm.generator.entity.BaseSuperEntity;
import cn.kgm.generator.entity.ColumnEntity;
import cn.kgm.generator.entity.GenDTO;
import cn.kgm.generator.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年12月19日 下午11:40:24
 */
public class GenUtils {

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        // API
        templates.add("template/api/Api.java.vm");
        templates.add("template/api/factory/FallbackFactory.java.vm");
        // DTO
        templates.add("template/dto/dto/SaveDTO.java.vm");
        templates.add("template/dto/dto/UpdateDTO.java.vm");
        templates.add("template/dto/query/PageQuery.java.vm");
        templates.add("template/dto/vo/Vo.java.vm");
        templates.add("template/dto/entity/Entity.java.vm");
        // SERVER
        templates.add("template/server/controller/Controller.java.vm");
        templates.add("template/server/mapper/Mapper.java.vm");
        templates.add("template/server/service/Service.java.vm");
        templates.add("template/server/service/impl/ServiceImpl.java.vm");
        templates.add("template/server/struct/MapStruct.java.vm");
        // XML
        templates.add("template/resources/Mapper.xml.vm");
        // TEST
        templates.add("template/test/TestService.java.vm");

        return templates;
    }

    /**
     * 单表生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns,
                                     ZipOutputStream zip,
                                     GenDTO genParam) {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        boolean hasList = false;
        //表信息
        TableEntity tableEntity = new TableEntity();
        String basePackageName = StrUtil.isEmpty(genParam.getBasePackageName()) ? config.getString("package") : genParam.getBasePackageName();
        String moduleName = StrUtil.isEmpty(genParam.getModuleName()) ? config.getString("moduleName") : genParam.getModuleName();
        String author = StrUtil.isEmpty(genParam.getAuther()) ? config.getString("author") : genParam.getAuther();
        String[] tablePrefix = ArrayUtil.isEmpty(genParam.getTablePrefix()) ? config.getStringArray("tablePrefix") : genParam.getTablePrefix();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));
        //表名转换成Java类名
        // tablePrefix =  表前缀
        String className = tableToJava(tableEntity.getTableName(),
                tablePrefix);
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            Long max = Long.valueOf(String.valueOf(Objects.isNull(column.get("characterMaximumLength")) ? "0" : column.get("characterMaximumLength")));
            if (max > Integer.MAX_VALUE) {
                max = (long) Integer.MAX_VALUE;
            }
            columnEntity.setCharacterMaximumLength(String.valueOf(0 == max ? null : max));
            columnEntity.setTableComment(CharSequenceUtil.replace(table.get("tableComment"), "\n", "\n * "));
            columnEntity.setComments(CharSequenceUtil.replace(column.get("columnComment"), "\n", "\n     * "));
            columnEntity.setExtra(column.get("extra"));
            columnEntity.setColumnComment(CharSequenceUtil.replace(column.get("columnComment"), "\n", "\n     * "));
            columnEntity.setAttrComment(CharSequenceUtil.subBefore(column.get("columnComment"), "\n", false).trim());

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), columnToJava(columnEntity.getDataType()));
            columnEntity.setAttrType(attrType);


            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasList && "array".equals(columnEntity.getExtra())) {
                hasList = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        // 判断表字段是否包含基础实体类字段
        tableEntity.setSuperEntity(BaseSuperEntity.NONE);
        List<String> columnNameList = columsList.stream().map(ColumnEntity::getColumnName).collect(Collectors.toList());
        if (columnNameList.containsAll(BaseSuperEntity.BASE_ENTITY.getSuperColumnList())) {
            tableEntity.setSuperEntity(BaseSuperEntity.BASE_ENTITY);
        }
        //没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        String mainPath = config.getString("mainPath");
        mainPath = StringUtils.isBlank(mainPath) ? "cn.kgm" : mainPath;
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("classComment", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasList", hasList);
        map.put("mainPath", mainPath);
        map.put("package", basePackageName);
        map.put("moduleName", moduleName);
        map.put("author", author);
        map.put("feignPrefix", config.getString("feignPrefix"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        map.put("superEntity", tableEntity.getSuperEntity());
        map.put("idType", tableEntity.getPk().getAttrType());
        map.put("tableComment", table.get("tableComment"));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(Objects.requireNonNull(getFileName(template, tableEntity.getClassName(), basePackageName, moduleName))));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RRException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String[] tablePrefixArray) {
        if (null != tablePrefixArray && tablePrefixArray.length > 0) {
            for (String tablePrefix : tablePrefixArray) {
                if (tableName.startsWith(tablePrefix)) {
                    tableName = tableName.replaceFirst(tablePrefix, "");
                }
            }
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RRException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     * dto
     * api
     * server
     */
    public static String getFileName(String template, String className, String packageName, String moduleName) {
        // main/java
        String server = "main/server" + File.separator + "java" + File.separator;
        String api = "main/api" + File.separator + "java" + File.separator;
        String dto = "main/dto" + File.separator + "java" + File.separator;
        // test/java
        String test = "test" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            server += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
            dto += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
            api += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
            test += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }
        // API
        if (template.contains("/Api.java.vm")) {
            return api + "api" + File.separator + className + "FeignApi.java";
        }
        if (template.contains("/FallbackFactory.java.vm")) {
            return api + "api/factory" + File.separator + className + "FallbackFactory.java";
        }
        // DTO
        if (template.contains("/SaveDTO.java.vm")) {
            return dto + "dto" + File.separator + "dto" + File.separator + className + "SaveDTO.java";
        }
        if (template.contains("/UpdateDTO.java.vm")) {
            return dto + "dto" + File.separator + "dto" + File.separator + className + "UpdateDTO.java";
        }
        if (template.contains("/PageQuery.java.vm")) {
            return dto + "dto" + File.separator + "query" + File.separator + className + "PageQuery.java";
        }
        if (template.contains("/Vo.java.vm")) {
            return dto + "dto" + File.separator + "vo" + File.separator + className + "VO.java";
        }
        if (template.contains("/Entity.java.vm")) {
            return dto + "dto" + File.separator + "entity" + File.separator + className + ".java";
        }
        //SERVER

        if (template.contains("/MapStruct.java.vm")) {
            return server + "server" + File.separator + "struct" + File.separator + className + "Mappers.java";
        }
        if (template.contains("/Controller.java.vm")) {
            return server + "server" + File.separator + "controller" + File.separator + className + "Controller.java";
        }
        if (template.contains("/Service.java.vm")) {
            return server + "server" + File.separator + "service" + File.separator + className + "Service.java";
        }
        if (template.contains("/ServiceImpl.java.vm")) {
            return server + "server" + File.separator + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }
        if (template.contains("/Mapper.java.vm")) {
            return server + "server" + File.separator + "mapper" + File.separator + className + "Mapper.java";
        }
        // MAPPER.XML
        if (template.contains("/Mapper.xml.vm")) {
            return "main/server" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
        }
        // TestController
        if (template.contains("/TestService.java.vm")) {
            return test + "server" + File.separator + "controller" + File.separator + className + "TestService.java";
        }
        return null;
    }
}
